import { React, useState, useEffect } from 'react'
import {Button, Form, Input, Toast} from 'antd-mobile'
import { ExclamationShieldOutline, LeftOutline } from 'antd-mobile-icons'
import '../Pay/pay.css'
import {getInfo, user_recharge} from '../../request/api'
import {useLocation, useNavigate} from "react-router-dom";
import QRCode from "qrcode.react";
import { useTranslation } from "react-i18next";
export default function UserPay() {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [val, setVal] = useState('')
  const [money, setMoney] = useState('')
  const location = useLocation();
  const type = location.state || 0;
  const getuserinfo = ()=>{
    getInfo({}).then(res =>{
      if (res.code == 0){
        setVal(res.data.master_cardnum)
      }
    })
  }

  const submit = ()=>{
    if (!money){
      return Toast.show({
        icon: 'fail',
        content: t('cz7'),
        duration: 2500
      })
    }
    user_recharge({
      type: type,
      num: money
    }).then(res =>{
      if (res.code == 0){
        Toast.show({
          icon: 'success',
          content: res.info,
          duration: 2500
        })
        navigate('/Recharge')
      }
    })
  }

  function limitToTwoDecimalPlaces(value) {
    // 移除非数字和小数点的字符
    value += ''
    value = value.replace(/[^\d.]/g, '');

    // 限制只有一个小数点
    value = value.replace(/^(\d+)\./g, '$1.');
    value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');

    // 限制小数点后只能有两个数字
    value = value.replace(/(\d)\.(\d{3})/, '$1.$2');

    // 如果值为0开头，则允许输入小数点
    value = value.replace(/^0+(?=\d)/g, '');


    // 如果小数点后有超过两位数字，则去掉多余的数字
    var temp = value.split('.');
    if (temp.length > 1 && temp[1].length > 2) {
      value = temp[0] + '.' + temp[1].substr(0, 2);
    }
    return value
  }
  useEffect(() => {
    getuserinfo()
  }, [])
  return (
      <div className='UserPay'>
        <div className='header'>
          <div className='backIcon' onClick={() => { navigate('/User') }}>
            <LeftOutline />
          </div>
          <p>{t('g2')}</p>
        </div>
        {
            type == 2 && <div className='UserPay_box'>
            <div className='userPay_top'>
              <img src="/assets/index/trc20.png" alt="" />
              <p>TRC-20</p>
            </div>
            <div className='qrcode'>
              <div>
                <ExclamationShieldOutline style={{ color: '#000', margin: '3px 3px 0' }} />
                <p>{t('cz5', {num: 20})}</p>
              </div>
              <div className='code'>
                {val && <QRCode
                    id={'qrCode'}
                    value={val}  //value参数为生成二维码的链接
                    size={180} //二维码的宽高尺寸
                    fgColor="#000000"  //二维码的颜色
                />}
              </div>
              <div className='payCode'>
                <p>{val}</p>
              </div>
              <div className='copy' onClick={() => {
                navigator.clipboard.writeText(val).then(() => {
                  Toast.show({
                    icon: 'success',
                    content: t('t2'),
                  })
                });
              }}>
                <p>{t('cz2')}</p>
              </div>
            </div>
          </div>
        }

        <div className="recharge">
          <Form layout='horizontal'>
            <Form.Item label={t('cz8')}>
              <Input value={money} placeholder={t("cz7")} onChange={(val) => {
                val = limitToTwoDecimalPlaces(val)
                setMoney(val)
              }} clearable/>
            </Form.Item>
          </Form>
          <Button className="pay-money" shape='default' block color='primary' onClick={submit}>
            {t('ty3')}
          </Button>
        </div>
      </div>
  )
}
